<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form size="small" :inline="true" @submit.native.prevent>
      <el-form-item label="设备编号">
        <el-input
          v-model="searchForm.deviceCode"
          clearable
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="mini"
          @click="handleSearch('搜索')"
          class="button"
          plain
          >搜索</el-button
        >
        <el-button
          type="info"
          size="mini"
          @click="handleReset"
          class="button"
          plain
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          size="mini"
          @click="handleAdd()"
          plain
          v-hasPermi="['approveEmail_add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="mini"
          @click="handleDelete()"
          plain
          :disabled="multiple"
          v-hasPermi="['approveEmail_delete']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          @click="handleImport()"
          v-hasPermi="['approveEmail_upload']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="handleExport()"
          v-hasPermi="['approveEmail_export']"
          >导出</el-button
        >
      </el-col>
    </el-row>
    <!-- 表 -->
    <el-table
      v-loading="loading"
      :data="tableList"
      border
      :max-height="THeight"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed />
      <el-table-column label="序号" align="center" prop="index" width="50" />
      <el-table-column label="设备编号" align="center" prop="deviceCode" />
      <el-table-column
        label="FACA工程师"
        align="center"
        prop="FACA1"
        width="130"
      />
      <el-table-column label="FACA课长" align="center" prop="FACA2" />
      <el-table-column label="FACA部长" align="center" prop="FACA3" />
      <el-table-column label="QC工程师" align="center" prop="QC1" width="130" />
      <el-table-column label="QC课长" align="center" prop="QC2" />
      <el-table-column label="QC部长" align="center" prop="QC3" />
      <el-table-column label="QA部长" align="center" prop="QA1" />
      <el-table-column label="QA本部长" align="center" prop="QA2" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleEdit(scope.row)"
            v-hasPermi="['approveEmail_edit']"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <pagination
      :total="total"
      :page.sync="Page.pageNum"
      :limit.sync="Page.pageSize"
      @pagination="getInfo()"
    />
    <!-- dialog -->
    <el-dialog
      :title="title"
      :visible.sync="Open"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="dialogCancel"
    >
      <div style="color: #e6a23c">下拉框数据源于“邮件维护”页面</div>
      <el-card style="margin-top: 10px">
        <el-form
          ref="form"
          :model="form"
          label-position="left"
          :rules="rules"
          label-width="88px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="设备编号" prop="deviceCode"
                ><el-input
                  v-model="form.deviceCode"
                  clearable
                  placeholder="请输入"
                  style="width: 216px"
                ></el-input
              ></el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="FACA工程师" prop="FACA1" label-width="105px">
                <el-select
                  v-model="form.FACA1"
                  placeholder="请选择"
                  filterable
                  clearable
                  multiple
                >
                  <el-option
                    v-for="item in Prefix_dept.FACA工程师"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option> </el-select></el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="FACA课长" prop="FACA2">
                <el-select
                  v-model="form.FACA2"
                  placeholder="请选择"
                  filterable
                  clearable
                  multiple
                >
                  <el-option
                    v-for="item in Prefix_dept.FACA课长"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option> </el-select></el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="FACA部长" prop="FACA3" label-width="105px">
                <el-select
                  v-model="form.FACA3"
                  placeholder="请选择"
                  filterable
                  clearable
                  multiple
                >
                  <el-option
                    v-for="item in Prefix_dept.FACA部长"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="QC工程师" prop="QC1">
                <el-select
                  v-model="form.QC1"
                  placeholder="请选择"
                  filterable
                  clearable
                  multiple
                >
                  <el-option
                    v-for="item in Prefix_dept.QC工程师"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="QC课长" prop="QC2" label-width="105px">
                <el-select
                  v-model="form.QC2"
                  placeholder="请选择"
                  filterable
                  clearable
                  multiple
                >
                  <el-option
                    v-for="item in Prefix_dept.QC课长"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="QC部长" prop="QC3">
                <el-select
                  v-model="form.QC3"
                  placeholder="请选择"
                  filterable
                  clearable
                  multiple
                >
                  <el-option
                    v-for="item in Prefix_dept.QC部长"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="QA部长" prop="QA1" label-width="105px">
                <el-select
                  v-model="form.QA1"
                  placeholder="请选择"
                  filterable
                  clearable
                  multiple
                >
                  <el-option
                    v-for="item in Prefix_dept.QA部长"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item label="QA本部长" prop="QA2">
                <el-select
                  v-model="form.QA2"
                  placeholder="请选择"
                  filterable
                  clearable
                  multiple
                >
                  <el-option
                    v-for="item in Prefix_dept.QA本部长"
                    :key="item"
                    :label="item"
                    :value="item"
                  >
                  </el-option>
                </el-select> </el-form-item
            ></el-col>
          </el-row>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer" v-show="title != '维护详情'">
        <el-button type="info" plain size="mini" @click="dialogCancel"
          >取 消</el-button
        >
        <el-button type="success" plain size="mini" @click="dialogSubmit"
          >保 存</el-button
        >
      </div>
    </el-dialog>
    <!-- 文件导入 -->
    <UploadExcel
      ref="child"
      moban="approveEmail"
      :relations="relations"
      @child-event="ImportFile"
    ></UploadExcel>
  </div>
</template>

<script>
import moment from "moment";
import XLSX from "xlsx";
import {
  reqAddDeviceMail,
  reqGetMailInfo,
  reqEditDeviceMail,
  reqDelDeviceMail,
  requploadExcel,
  reqOptsList,
} from "@/api/newApi/OCAP";
export default {
  components: {
    UploadExcel: () => import("@/views/components/uploadExcel"),
  },
  data() {
    return {
      THeight: null,
      loading: false,
      searchForm: {},
      Page: { pageNum: 1, pageSize: 20 },
      tableList: [],
      total: 0,
      Open: false,
      title: "",
      multiple: false,
      form: {},
      rules: {
        deviceCode: { required: true, message: "必填项", trigger: "blur" },
      },
      form1: {},
      nowIds: "",
      oldDeviceCode: "",
      deviceCodes: [],
      //文件导入字段名中英文关系
      relations: {
        设备编号: "deviceCode",
        FACA工程师: "FACA1",
        FACA课长: "FACA2",
        FACA部长: "FACA3",
        QC工程师: "QC1",
        QC课长: "QC2",
        QC部长: "QC3",
        QA部长: "QA1",
        QA本部长: "QA2",
      },
      Prefix_dept: {
        FACA工程师: [],
        FACA课长: [],
        FACA部长: [],
        QC工程师: [],
        QC课长: [],
        QC部长: [],
        QA部长: [],
        QA本部长: [],
      },
    };
  },
  mounted() {
    this.getInfo();
    this.OptsList();
  },
  methods: {
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.deviceCodes = selection
        .map((item) => item.deviceCode)
        .sort((a, b) => b - a);
      this.multiple = !selection.length; // 非多个禁用
    },
    //获取数据
    async getInfo(name) {
      let reqObj = { ...this.Page, ...this.searchForm };
      let res = await reqGetMailInfo(reqObj);
      if (res.code == 200) {
        //删除res.info中的hasDept字段
        res.info.forEach((item) => {
          delete item.hasDept;
        });
        this.tableList = res.info;
        this.total = res.total;
        if (name == "搜索") {
          this.$message.success("查询成功");
        }
      } else {
        this.$message.error(res.msg);
      }
    },
    //获取下拉框
    async OptsList() {
      let res = await reqOptsList({
        Method: "select",
        Value: {},
      });
      if (res.Result == 1) {
        res.Value.forEach((item) => {
          const prefix = item.Prefix_dept;
          const driList = item.DRI_List;
          if (this.Prefix_dept.hasOwnProperty(prefix)) {
            this.Prefix_dept[prefix] = driList;
          }
        });
      } else {
        this.$message.error(res.Value);
      }
      // console.log(this.Prefix_dept, "++++++++++");
    },
    //搜索
    handleSearch(name) {
      this.Page.pageNum = 1;
      this.getInfo(name);
    },
    //重置
    handleReset() {
      this.searchForm = {};
      this.handleSearch();
    },
    handleAdd() {
      this.form = {};
      this.Open = true;
      this.title = "新增";
    },
    async handleDelete() {
      this.$modal
        .confirm(
          '是否确认删除设备编号为"' +
            this.deviceCodes.toString() +
            '"的数据项？'
        )
        .then(() => {
          reqDelDeviceMail(this.deviceCodes).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.getInfo();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {});
    },
    handleEdit(row) {
      this.Open = true;
      this.title = "修改";
      this.form = {
        ...row,
        FACA1: row.FACA1 == "" ? [] : row.FACA1.split(","),
        FACA2: row.FACA2 == "" ? [] : row.FACA2.split(","),
        FACA3: row.FACA3 == "" ? [] : row.FACA3.split(","),
        QC1: row.QC1 == "" ? [] : row.QC1.split(","),
        QC2: row.QC2 == "" ? [] : row.QC2.split(","),
        QC3: row.QC3 == "" ? [] : row.QC3.split(","),
        QA1: row.QA1 == "" ? [] : row.QA1.split(","),
        QA2: row.QA2 == "" ? [] : row.QA2.split(","),
      };
      this.oldDeviceCode = JSON.parse(JSON.stringify(row.deviceCode));
    },
    dialogCancel() {
      this.Open = false;
      this.form = {};
    },
    dialogSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let reqObj = {
            ...this.form,
            FACA1: this.form.FACA1.toString(),
            FACA2: this.form.FACA2.toString(),
            FACA3: this.form.FACA3.toString(),
            QC1: this.form.QC1.toString(),
            QC2: this.form.QC2.toString(),
            QC3: this.form.QC3.toString(),
            QA1: this.form.QA1.toString(),
            QA2: this.form.QA2.toString(),
          };
          if (this.title === "新增") {
            reqAddDeviceMail(reqObj).then((res) => {
              if (res.code === 200) {
                this.$message.success("添加成功");
                this.Open = false;
                this.getInfo();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else if (this.title === "修改") {
            reqObj.oldDeviceCode = this.oldDeviceCode;
            reqEditDeviceMail({
              ...reqObj,
              oldDeviceCode: this.oldDeviceCode,
            }).then((res) => {
              if (res.code === 200) {
                this.$message.success("修改成功");
                this.Open = false;
                this.getInfo();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        }
      });
    },
    //导入
    handleImport() {
      this.$refs.child.dialogOpen();
    },
    ImportFile(reqArr, fileItem) {
      if (fileItem.length == 0) {
        this.$modal.msgError("请选择文件");
      } else {
        var formData = new FormData();
        formData.append("file", fileItem);
        this.loading = true;
        this.$refs.child.uploadCancel();
        requploadExcel(formData)
          .then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess("导入成功");
            }
            if (res.EList.length != 0) {
              this.$alert(
                `<div style='overflow: auto;max-height: 70vh'>${res.EList.toString().replace(
                  /,/g,
                  "<br/>"
                )}</div>`,
                "Tips",
                { dangerouslyUseHTMLString: true }
              );
            }
            this.loading = false;
            this.getInfo();
          })
          .catch((err) => {
            this.$alert(`${err}`, "Tips", {});
            this.loading = false;
          });
      }
    },
    //导出
    async handleExport() {
      if (this.tableList.length > 0) {
        const loading = this.$loading({
          lock: true,
          text: `Loading`,
          spinner: "el-icon-loading",
        });
        try {
          const headers = [
            "设备编号",
            "FACA工程师",
            "FACA课长",
            "FACA部长",
            "QC工程师",
            "QC课长",
            "QC部长",
            "QA部长",
            "QA本部长",
          ];
          //前后去空格
          if (this.searchForm.deviceCode) {
            this.searchForm.deviceCode = this.searchForm.deviceCode.trim();
          }
          let Page = { pageSize: this.total, pageNum: 1 };
          let res = await reqGetMailInfo(Object.assign(this.searchForm, Page));
          const datas = res.info.map((item) => [
            item.deviceCode,
            item.FACA1,
            item.FACA2,
            item.FACA3,
            item.QC1,
            item.QC2,
            item.QC3,
            item.QA1,
            item.QA2,
            item.QA3,
          ]);
          const worksheet = XLSX.utils.aoa_to_sheet([headers, ...datas]);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, "sheet1");
          XLSX.writeFile(
            workbook,
            `审批管理${moment(new Date()).format("yyyy-MM-DD HH:mm")}.xlsx`
          );
        } catch (error) {
          console.error("导出数据失败:", error);
        } finally {
          loading.close();
        }
      } else {
        this.$modal.msgError("暂无数据可导出");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
//表头颜色
::v-deep .el-table .el-table__header-wrapper th,
.el-table .el-table__fixed-header-wrapper th {
  background-color: #f0f8ff !important;
}
//dialog
::v-deep .el-dialog__body {
  padding: 0 20px 10px 20px;
}
::v-deep .el-card__body {
  padding: 10px 10px 10px 10px;
}
::v-deep .el-tabs__item {
  padding: 0px 45px;
}
</style>